package com.kky.pp.activity.user

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.manager.SDActivityManager
import com.custom.base.mvp.BasePresenterImpl
import com.custom.base.util.IntentUtil
import com.kky.pp.common.Constant
import com.kky.pp.R
import com.kky.pp.adapter.PageLoaderStringAdapter
import com.kky.pp.callback.EmptyCallBack
import com.kky.pp.common.MemberBuy
import com.kky.pp.popup.UserClickMorePopup
import com.kky.pp.entity.BaseEntity
import com.kky.pp.entity.MatchResultEntity
import com.kky.pp.entity.UserProfileInfoEntity
import com.kky.pp.activity.fc.FlashChatActivity
import com.kky.pp.activity.match.MatchedActivity
import com.kky.pp.util.CollectionUtils
import com.kky.pp.util.DateUtils
import com.kky.pp.util.DensityUtil
import com.kky.pp.util.TextUtil
import com.kky.pp.view.GridLineIndicator
import com.custom.base.base.SDEventManager
import com.youth.banner.config.IndicatorConfig
import com.youth.banner.util.BannerUtils
import io.rong.imkit.IMCenter
import io.rong.imkit.dialog.UserProfileOperationReportDialog
import io.rong.imkit.event.EnumEventTag
import io.rong.imkit.event.FirebaseEventTag
import io.rong.imkit.utils.FirebaseEventUtils
import io.rong.imkit.utils.StatusBarUtil
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import java.util.stream.Collectors


/**
 * 作者：
 * 时间：
 * 描述：
 */
class UserProfileInfoPresenter : BasePresenterImpl<UserProfileInfoContract.View>(),
    UserProfileInfoContract.Presenter {
    var isIM = false

    override fun initBundle(bundle: Bundle) {
        isIM = bundle.getBoolean("isIM")
        mView?.apply {
            framePersonalInformationTopTitle.setPadding(
                0,
                StatusBarUtil.getStatusBarHeight(mActivity),
                0,
                0
            )
            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.user_user_info_url)
                    requestBody.add("userCode", bundle.getString("userCodeFriend", ""))
                }
            }, object : SDOkHttpResoutCallBack<UserProfileInfoEntity>() {
                override fun onSuccess(entity: UserProfileInfoEntity) {

                    conPersonalInformationBottomContainer.visibility =
                        if (bundle.getBoolean("isIM")) View.INVISIBLE else View.VISIBLE
                    val indicator = GridLineIndicator(mActivity)
                    indicator.setIndicatorWidth(DensityUtil.dp2px(mActivity, 16f))
                    bannerPersonalInformationList.indicator = indicator
                    bannerPersonalInformationList.setIndicatorMargins(
                        IndicatorConfig.Margins(
                            0, 0, BannerUtils.dp2px(9f).toInt(), BannerUtils.dp2px(12f).toInt()
                        )
                    )

                    if (CollectionUtils.isNotEmpty(entity.data.images)) {
                        bannerPersonalInformationList.adapter = PageLoaderStringAdapter(mActivity, entity.data.images)
                        bannerPersonalInformationList.currentItem = bundle.getInt("currentItem")
                    }
                    txtPersonalInformationStatus.visibility =
                        if (entity.data.online == 1) View.VISIBLE else View.GONE
                    txtPersonalInformationPositioning.visibility =
                        if (entity.data.nearby == 1) View.VISIBLE else View.GONE

                    val drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_index_member)
                    val drawable1 = ContextCompat.getDrawable(
                        mActivity,
                        if (entity.data.gender == 1) R.mipmap.icon_male else if (entity.data.gender == 2) R.mipmap.icon_female else R.mipmap.icon_gay_sex
                    )
                    txtPersonalInformationNickName.text = TextUtil().addIconsToText(
                        mActivity,
                        "${entity.data.nickName} · ${entity.data.age}",
                        if (entity.data.userType == 2) drawable1 else null,
                        drawable!!
                    )

                    txtPersonalInformationAboutMeTitle.visibility =
                        if (entity.data.aboutMe == "") View.GONE else View.VISIBLE
                    txtPersonalInformationIntroduce.text = entity.data.aboutMe

                    txtPersonalInformationHobbyTitle.visibility =
                        if (CollectionUtils.isEmpty(entity.data.interests)) View.GONE else View.VISIBLE
                    tagPersonalInformation.visibility =
                        if (CollectionUtils.isEmpty(entity.data.interests)) View.GONE else View.VISIBLE

                    if (CollectionUtils.isNotEmpty(entity.data.interests)) {
                        tagPersonalInformation.setTags(entity.data.interests)
                    }
                    val userWant =
                        entity.data.userWant.stream().filter { v -> v.selected == 1 }?.collect(
                            Collectors.toList()
                        )
                    if (userWant != null && userWant.size > 0) {
                        txtPersonalInformationPurpose.text = userWant[0].value
                    }

                    txtPersonalInformationHigh.isVisible = !TextUtils.isEmpty(entity.data.inchHeight)
                    txtPersonalInformationConstellation.isVisible = !TextUtils.isEmpty( entity.data.birthday)

                    if (!TextUtils.isEmpty(entity.data.inchHeight))
                        txtPersonalInformationHigh.text = entity.data.inchHeight
                    if (!TextUtils.isEmpty(entity.data.birthday)) {
                        txtPersonalInformationConstellation.text =
                            DateUtils.getConstellation(mActivity, entity.data.birthday)
                        setStarSign(entity)
                    }
                    if (CollectionUtils.isNotEmpty(entity.data.turnOnsList)) {
                        turnOnsViewPersonalInformationTitle.isVisible = true
                        turnOnsViewPersonalInformation.isVisible = true
                        turnOnsViewPersonalInformation.setBg()
//                        turnOnsViewPersonalInformation.viewTurnOnsBg?.setBackgroundResource(R.color.Transparent)
//                        turnOnsViewPersonalInformation.viewMore?.isVisible = false
                        turnOnsViewPersonalInformation.setData(entity.data.turnOnsList)
                    } else {
                        turnOnsViewPersonalInformationTitle.isVisible = false
                        turnOnsViewPersonalInformation.isVisible = false
                    }


                    imgViewPersonalInformationChat.setOnClickListener {
                        //参照meboo修改
                        val bun = Bundle()
                        bun.putString("userName", entity.data.nickName)
                        bun.putString("userCode", entity.data.userCode)
                        bun.putString("avatar", entity.data.avatarUrl)
                        IntentUtil.startActivity(FlashChatActivity::class.java, bun)
                        FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Profile_Flashchat.name)
//                        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
//                            override fun addBody(requestBody: OkHttpBodyEntity) {
//                                requestBody.setPost(Constant.user_reduce_benefits_url)
//                                requestBody.add("benefitCode", 1)
//                                requestBody.add(
//                                    "chatUserCode",
//                                    bundle.getString("userCodeFriend", "")
//                                )
//                            }
//                        }, object : SDOkHttpResoutCallBack<UserMemberStatusEntity>() {
//                            override fun onSuccess(data: UserMemberStatusEntity) {
//                                FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Profile_Flashchat.name)
//
//                                RongIM.getInstance().refreshUserInfoCache(
//                                    UserInfo(
//                                        entity.data.userCode,
//                                        entity.data.nickName,
//                                        Uri.parse(entity.data.avatarUrl)
//                                    )
//                                )
//                                RouteUtils.routeToConversationActivity(
//                                    mActivity,
//                                    Conversation.ConversationType.PRIVATE,
//                                    entity.data.userCode,
//                                    true
//                                )
//                                SDEventManager.post(EnumEventTag.INDEX_MATCH_REFRESH_DATA.ordinal)
//                                SDEventManager.post(true, EnumEventTag.INDEX_LIKE_SWIPED.ordinal)
//
//                            }
//
//                            override fun onFailure(code: Int, msg: String) {
//                                when(code){
//                                    2003->{
//                                        FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Profile_Flash_chat_Sub.name)
//                                        MemberBuy().openMemberBuy(SDActivityManager.instance.lastActivity,1, callBackListener = {
//                                            FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Profile_Flash_chat_Subsuccess.name)
//                                        })
//                                    }
//                                    2002->{
//                                        FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Profile_Flash_chat_Buy.name)
//                                        MemberUnitaryBuy().openMemberUnitaryBuy(mActivity,2,callBackListener = {
//                                            FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Profile_Flash_chat_Buysuccess.name)
//                                        })
//                                    }
//                                }
//                            }
//                        })

                    }

                    imgViewPersonalInformationLike.setOnClickListener {
                        if (isIM)
                            return@setOnClickListener
                        if (bundle.getBoolean("isWlm")) {
                            benefitsReduceWLM(
                                bundle.getString("userCodeFriend", ""),
                                1,
                                object : EmptyCallBack {
                                    override fun OnSuccessListener() {
                                        OkHttpManager.instance.requestInterface(object :
                                            OkHttpFromBoy {
                                            override fun addBody(requestBody: OkHttpBodyEntity) {
                                                requestBody.setPost(Constant.user_add_wlm_url)
                                                requestBody.add("likeType", 1)
                                                requestBody.add(
                                                    "userCodeFriend",
                                                    bundle.getString("userCodeFriend", "")
                                                )
                                            }
                                        }, object : SDOkHttpResoutCallBack<MatchResultEntity>() {
                                            override fun onSuccess(entityMatch: MatchResultEntity) {
                                                FirebaseEventUtils.logEvent(FirebaseEventTag.WLM_Profile_Like.name)
                                                SDEventManager.post(
                                                    bundle.getInt("selectPosition"),
                                                    EnumEventTag.WLM_LIKE_SWIPED.ordinal
                                                )
                                                if (entityMatch.data.matched) {
                                                    val bundle = Bundle()
                                                    bundle.putString(
                                                        "userCodeFriend",
                                                        bundle.getString("userCodeFriend", "")
                                                    )
                                                    bundle.putString(
                                                        "avatarUrl",
                                                        entity.data.avatarUrl
                                                    )
                                                    startActivity(
                                                        MatchedActivity::class.java,
                                                        bundle
                                                    )
                                                }
                                                finish()
                                            }

                                            override fun onFailure(code: Int, msg: String) {
                                            }
                                        }, isShowDialog = false)
                                    }

                                    override fun OnFailListener() {

                                    }

                                })

                        } else {
                            FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Profile_Like.name)
                            SDEventManager.post(EnumEventTag.INDEX_LIKE_SWIPED.ordinal)
                            finish()
                        }
                    }
                }


                override fun onFailure(code: Int, msg: String) {
                }
            })

            imgViewPersonalInformationMenus.setOnClickListener {
                if (!isIM) {
                    FirebaseEventUtils.logEvent(if (!bundle.getBoolean("isWlm")) FirebaseEventTag.Home_Profile_More.name else FirebaseEventTag.WLM_Profile_More.name)
                }
                UserClickMorePopup(
                    mActivity,
                    bundle,
                    object : UserClickMorePopup.UserActionListener {
                        override fun userReport() {
                            if (!isIM)
                                FirebaseEventUtils.logEvent(if (!bundle.getBoolean("isWlm")) FirebaseEventTag.Home_Profile_Report.name else FirebaseEventTag.WLM_Profile_Report.name)
                            Handler().postDelayed({
                                UserProfileOperationReportDialog(
                                    mActivity,
                                    bundle.getString("userCodeFriend", ""),
                                    bundle.getBoolean("isWlm"),
                                    object :
                                        UserProfileOperationReportDialog.OnListener {
                                        override fun userReport() {
                                            if (!isIM)
                                                FirebaseEventUtils.logEvent(if (!bundle.getBoolean("isWlm")) FirebaseEventTag.Home_Profile_Reportsuccess.name else FirebaseEventTag.WLM_Profile_Reportsuccess.name)
                                            if (bundle.getBoolean("isIndex")) {
                                                Handler().postDelayed({
                                                    SDEventManager.post(EnumEventTag.INDEX_DISLIKE_SWIPED.ordinal)
                                                    mActivity.finish()
                                                }, 500)

                                            }
                                        }

                                    }).showPopupWindow()
                            }, 200)
                        }

                        override fun userBlack() {
                            if (!isIM)
                                FirebaseEventUtils.logEvent(if (!bundle.getBoolean("isWlm")) FirebaseEventTag.Home_Profile_Block.name else FirebaseEventTag.WLM_Profile_Block.name)
                            if (bundle.getBoolean("isWlm")) {
                                SDEventManager.post(
                                    bundle.getInt("selectPosition"),
                                    EnumEventTag.WLM_DISLIKE_SWIPED.ordinal
                                )
                            } else {
                                if (bundle.getBoolean("isIndex")) {
                                    SDEventManager.post(EnumEventTag.INDEX_DISLIKE_SWIPED.ordinal)
                                }
                            }
                            IMCenter.getInstance()
                                .removeConversation(
                                    Conversation.ConversationType.PRIVATE,
                                    bundle.getString("userCodeFriend", ""),
                                    null
                                )

                            RongIMClient.getInstance().deleteMessages(
                                Conversation.ConversationType.PRIVATE,
                                bundle.getString("userCodeFriend", ""),
                                null
                            )
                            mActivity.finish()
                        }

                    }).showPopupWindow()
            }

            imgViewPersonalInformationUnLike.setOnClickListener {
                if (isIM)
                    return@setOnClickListener
                if (bundle.getBoolean("isWlm")) {
                    benefitsReduceWLM(
                        bundle.getString("userCodeFriend", ""),
                        1,
                        object : EmptyCallBack {
                            override fun OnSuccessListener() {
                                OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                                    override fun addBody(requestBody: OkHttpBodyEntity) {
                                        requestBody.setPost(Constant.user_add_wlm_url)
                                        requestBody.add("likeType", 2)
                                        requestBody.add(
                                            "userCodeFriend",
                                            bundle.getString("userCodeFriend", "")
                                        )
                                    }
                                }, object : SDOkHttpResoutCallBack<MatchResultEntity>() {
                                    override fun onSuccess(entity: MatchResultEntity) {
                                        FirebaseEventUtils.logEvent(FirebaseEventTag.WLM_Profile_Pass.name)

                                        SDEventManager.post(
                                            bundle.getInt("selectPosition"),
                                            EnumEventTag.WLM_DISLIKE_SWIPED.ordinal
                                        )
                                        finish()
                                    }

                                    override fun onFailure(code: Int, msg: String) {
                                    }
                                }, isShowDialog = false)
                            }

                            override fun OnFailListener() {

                            }

                        })
                } else {
                    FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Profile_Pass.name)
                    SDEventManager.post(EnumEventTag.INDEX_DISLIKE_SWIPED.ordinal)
                    mActivity.finish()
                }
            }


        }
    }

    fun benefitsReduceWLM(friendUserCode: String, type: Int, callBack: EmptyCallBack) {
        return OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.user_benefits_reduceWLM_url)
                requestBody.add("likeType", type)
                requestBody.add("userCodeFriend", friendUserCode)
            }
        }, object : SDOkHttpResoutCallBack<BaseEntity>() {
            override fun onSuccess(entity: BaseEntity) {
                callBack.OnSuccessListener()
            }

            override fun onFailure(code: Int, msg: String) {
                when (code) {
                    2003 -> {
                        MemberBuy().openMemberBuy(
                            SDActivityManager.instance.lastActivity,
                            1,
                            callBackListener = {
                            })
                    }
                }
            }
        }, isShowDialog = false)

    }

    /**
     * 设置星座
     */
    private fun setStarSign(entity: UserProfileInfoEntity) {
        mView?.apply {
            if (entity.data.birthday != null && entity.data.birthday != "") {
                val month = Integer.parseInt(DateUtils.getDateString(entity.data.birthday, "MM"))
                val day = Integer.parseInt(DateUtils.getDateString(entity.data.birthday, "dd"))
                var drawable: Drawable? = null
                if (month == 1 && day >= 20 || month == 2 && day <= 18) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_1)
                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_1)
                } else if (month == 2 && day >= 19 || month == 3 && day <= 20) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_2)

                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_2)
                } else if (month == 3 && day >= 21 || month == 4 && day <= 19) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_3)

                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_3)
                } else if (month == 4 && day >= 20 || month == 5 && day <= 20) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_4)

                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_4)
                } else if (month == 5 && day >= 21 || month == 6 && day <= 21) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_5)

                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_5)
                } else if (month == 6 && day >= 22 || month == 7 && day <= 22) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_6)

                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_6)
                } else if (month == 7 && day >= 23 || month == 8 && day <= 22) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_7)

                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_7)
                } else if (month == 8 && day >= 23 || month == 9 && day <= 22) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_8)

                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_8)
                } else if (month == 9 && day >= 23 || month == 10 && day <= 22) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_9)

                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_9)
                } else if (month == 10 && day >= 23 || month == 11 && day <= 21) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_10)

                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_10)
                } else if (month == 11 && day >= 22 || month == 12 && day <= 21) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_11)

                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_11)
                } else if (month == 12 && day >= 22 || month == 1 && day <= 19) {
                    txtPersonalInformationConstellation.text = mActivity.getString(R.string.star_sign_12)
                    drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_star_sign_12)
                }

                val drawableWidth = 23
                val drawableHeight = 23
                drawable!!.setBounds(0, 0, drawableWidth, drawableHeight)
                txtPersonalInformationConstellation.setCompoundDrawablesWithIntrinsicBounds(
                    drawable,
                    null,
                    null,
                    null
                )
            }
        }
    }

}